<?php
/**
 * Created by PhpStorm.
 * User: CYJiao
 * Date: 6/5/15
 * Time: 16:03
 */

class MedicineController extends Controller
{

    /**
     * Method returning filters array.
     */
    public function filters()
    {
        return array(
            'accessControl',//Performs access control for CRUD operations
        );
    }

    /**
     * Defines User Access Level.
     */
    public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array(),//Actions allowed
                'roles'=>array('@'),//Roles allowed to perform actions
            ),
            array('deny',
                'actions'=>array(),//Actions not allowed
                'roles'=>array('*'),//Roles not allowed to perform actions
            ),

        );
    }


    /******************************************************************************************
     * Following functions are related to medicine
     ******************************************************************************************/

    /**
     * Get Medicine
     */
    public function actionGetMedicine(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->render('list');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionAddmedicine(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->render('add');
        }
        else
            $this->redirect(array('site/login'));// View redirection

    }

    public function actionManage(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->render('manage');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    /**
     * Get Chinese Medicine
     */
    public function actionGetChineseMedicine(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->render('chinesemedicine');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    /**
     * Get Western Medicine
     */
    public function actionGetWesternMedicine(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $this->render('westernmedicine');
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionSearchall(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
             if($_POST['product_name_ch_ab'] != ''){

             }elseif($_POST['product_name_ch'] != ''){
                $medicines = MdWesternMedicine::model()->findAllByAttributes(array('product_name_ch'=>$_POST['product_name_ch']));
                $result = array();
                foreach ($medicines as $key => $medicine) {
                    $result[$key]['product_name_ch'] = $medicine['product_name_ch'];
                    $result[$key]['product_name_en'] = $medicine['product_name_en'];
                    $result[$key]['specification'] = $medicine['specification'];
                    $result[$key]['efficacy'] = $medicine['efficacy'];
                    $result[$key]['pharmaco'] = $medicine['pharmaco'];
                    $result[$key]['side_effect'] = $medicine['side_effect'];
                }

                //Action logging
                // $log = new Log600100(); //Create new empty record
                // $log->action = 'search_westermedicine';//Saving the action type
                // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                // $log->target = '';//针对对象
                // $log->save(false);//Saving the entire record with validation
                //var_dump($medicines[0]['product_name_ch']);
                echo json_encode($result);


             }else{
                echo json_encode(array());
             }
        }
        else
            $this->redirect(array('site/login'));// View redirection
       
    }

    public function actionGetwestern_(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);

            $db = $conn->o2omedicine;

            $collection = $db->selectCollection('md_medicine');
            $page_rows = empty($_POST['rows']) ? 20 : (int)$_POST['rows'];
            $offet = max(0,(int)($_POST['page'] - 1) * $page_rows);
            $condition['medicine_name'] = empty($_POST['medicine_name']) ? array() : new MongoRegex("/.*".$_POST['medicine_name'].".*/i");
            if(empty($condition['medicine_name'])) unset($condition['medicine_name']);
            $cursor = $collection->find($condition)->sort(array("update_time" => -1))->limit($page_rows)->skip($offet);
            $result = array();
            $rows = array();
            while ($cursor->hasNext()) {
                $rows[] = $cursor->getNext();
            }
            $result['total'] = $collection->count();
            $result['rows'] = $rows;

            // $log = new Log600100(); //Create new empty record
            // $log->action = 'search_mongowestermedicine';//Saving the action type
            // $log->create_time = new CDbExpression('NOW()');//Saving date and time
            // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
            // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
            // $log->target = '';//针对对象
            // $log->save(false);//Saving the entire record with validation

            echo json_encode($result);
            
        }
        else
            $this->redirect(array('site/login'));// View redirection
       
    }

    public function actionDelwestern_(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $result = array('status'=>0,'result'=>0);

            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omedicine;
            $collection = $db->selectCollection('md_medicine');

            $newdata = $_POST['newdata'];
            $newdata_arr = json_decode($newdata,true);
            $id = $newdata_arr[0]['_id']['$id'];
            $id = new MongoID($id);

            foreach ($newdata_arr as $key => $newdata) {
                $id = $newdata['_id']['$id'];
                $id = new MongoID($id);
                $collection->remove(array('_id' => $id), array("justOne" => true));

                // $log = new Log600100(); //Create new empty record
                // $log->action = 'del_westermedicine';//Saving the action type
                // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                // $log->target = $id;//针对对象
                // $log->save(false);//Saving the entire record with validation

            }

            echo json_encode($result);
            

        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionAddwestern_(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $result = array('status'=>0,'result'=>0);
            $newdata = $_POST['newdata'];
            $newdata_arr = json_decode($newdata,true);

            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omedicine;
            $collection = $db->selectCollection('md_medicine');

            foreach ($newdata_arr as $key => $newdata) {
               $collection->insert($newdata);

                // $log = new Log600100(); //Create new empty record
                // $log->action = 'add_westermedicine';//Saving the action type
                // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                // $log->target = '';//针对对象
                // $log->save(false);//Saving the entire record with validation

            }

            echo json_encode($result);
        
        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    public function actionUpwestern_(){
        if(isset(Yii::app()->session['status']) && Yii::app()->session['status'] == 'logged') {
            $result = array('status'=>0,'result'=>0);
            $newdata = $_POST['newdata'];
            $newdata_arr = json_decode($newdata,true); 

            $conn = new mongoClient($GLOBALS['mongodb']['connectionString']);
            $db = $conn->o2omedicine;
            $collection = $db->selectCollection('md_medicine');
            foreach ($newdata_arr as $key => $newdata) {
                $newdata['update_time'] = time();
                $id = $newdata['_id']['$id'];
                $id = new MongoID($id);
                unset($newdata['_id']);
                $collection->update(array('_id' => $id), array('$set' =>$newdata));

                // $log = new Log600100(); //Create new empty record
                // $log->action = 'add_westermedicine';//Saving the action type
                // $log->create_time = new CDbExpression('NOW()');//Saving date and time
                // $log->user_ip = Yii::app()->request->UserHostAddress;//Saving ip_address
                // $log->fk_user_id = Yii::app()->session['id'];//Saving user id
                // $log->target = $id;//针对对象
                // $log->save(false);//Saving the entire record with validation
            }

            echo json_encode($result);
            

        }
        else
            $this->redirect(array('site/login'));// View redirection
    }

    function actionTest(){//测试获取拼音首字母
        echo 111;
        $py = new str2PY();
        $test = '你们知道我是谁吗';
        $result = $py->getInitials($test);
        
        echo strtolower($result);
    }

}